#include <windows.h>
#include <ocidl.h>
#include <stdio.h>
#include "RealICompare.h"

void main()
{
    HRESULT hr;

    hr = CoInitialize(NULL);
    if (FAILED(hr))
    {
        fprintf(stderr, "CoInitialize failed with error code: %x\n", hr);
        return;
    }

    ISort *sort;
    hr = CoCreateInstance(CLSID_ISort, NULL, CLSCTX_INPROC_SERVER, IID_ISort, (LPVOID *)&sort);
    if (FAILED(hr))
    {
        fprintf(stderr, "CoCreateInstance failed with error code: %x\n", hr);
        CoUninitialize();
        return;
    }

    IConnectionPointContainer *container;
    hr = sort->QueryInterface(IID_IConnectionPointContainer, (void **)&container);
    if (FAILED(hr))
    {
        fprintf(stderr, "QueryInterface failed with error code: %x\n", hr);
        sort->Release();
        CoUninitialize();
        return;
    }

    IConnectionPoint *point;
    hr = container->FindConnectionPoint(DIID_ICompare, &point);
    container->Release();
    if (FAILED(hr))
    {
        fprintf(stderr, "FindConnectionPoint failed with error code: %x\n", hr);
        sort->Release();
        CoUninitialize();
        return;
    }

    DWORD cookie;
    hr = point->Advise(&compare, &cookie);
    if (FAILED(hr))
    {
        fprintf(stderr, "Advise failed with error code: %x\n", hr);
        point->Release();
        sort->Release();
        CoUninitialize();
        return;
    }

    DWORD dwArray[5] = {2, 3, 1, 5, 4};
    hr = sort->Sort(dwArray, 5, sizeof(DWORD));
    if (FAILED(hr))
    {
        fprintf(stderr, "Sort failed with error code: %x\n", hr);
        point->Release();
        sort->Release();
        CoUninitialize();
        return;
    }

    printf("sorted array:");
    for (int i = 0; i < _countof(dwArray); ++i)
        printf(" %d", dwArray[i]);
    printf("\n");

    hr = point->Unadvise(cookie);
    if (FAILED(hr))
    {
        fprintf(stderr, "Unadvise failed with error code: %x\n", hr);
    }

    point->Release();
    sort->Release();
    CoUninitialize();
}